<template>
  <el-dialog :title="title" v-model="visible" class="dialog-sm" append-to-body @close="visible = false">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" v-loading="loading">
      <el-form-item label="上级部门" prop="parent_id" v-if="form.id !== rootDept">
        <el-tree-select
          v-model="form.parent_id"
          filterable
          :data="deptOptions"
          :props="{ value: 'id', label: 'name', children: 'children' }"
          value-key="id"
          placeholder="选择上级部门"
          check-strictly />
      </el-form-item>
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入部门名称" maxlength="64" />
      </el-form-item>
      <el-form-item label="负责人" prop="leader">
        <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="32" />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="32" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="64" />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="显示排序" prop="list_sort">
            <el-input-number v-model="form.list_sort" controls-position="right" :min="0" class="w-full" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio v-for="dict in sys_normal_disable" :value="dict.value">{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="250" />
      </el-form-item>
    </el-form>
    <div class="dialog-footer slot">
      <el-button class="medium" type="primary" :loading="submitting" :disabled="loading" @click="handleSubmit"
        >确 定</el-button
      >
      <el-button class="medium" @click="visible = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script setup name="DeptForm">
  import { infoDeptApi, editDeptApi, addDeptApi, selectDeptApi } from '@/api/system/dept'

  const props = defineProps({ row: Object, moduleName: String })
  const visible = defineModel()
  const { proxy } = getCurrentInstance()

  const data = reactive({
    title: '',
    loading: false,
    submitting: false,
    deptOptions: [],
    form: {
      name: undefined,
      parent_id: undefined,
      leader: '',
      phone: '',
      email: '',
      status: '1',
      list_sort: 10,
      remark: ''
    },
    rules: {
      parent_id: [{ required: true, message: '上级部门不能为空', trigger: 'blur' }],
      name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
      list_sort: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
      status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
      // email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
      // phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
    }
  })

  const formRef = useTemplateRef('formRef')

  const { title, loading, submitting, deptOptions, form, rules } = toRefs(data)
  const { sys_normal_disable } = proxy.useDict('sys_normal_disable')
  const rootDept = proxy.useInitLoad('root_dept_id')

  // 初始化
  onMounted(async () => {
    loading.value = true
    form.value.id = props.row?.id || undefined
    if (form.value.id) {
      title.value = '编辑' + props.moduleName
      await getRowData()
    } else {
      title.value = '添加' + props.moduleName
      form.value.parent_id = props.row?.parent_id || undefined
    }
    await getDeptOptions()
    loading.value = false
  })

  // 获取信息
  async function getRowData() {
    try {
      const { info } = await infoDeptApi(form.value.id)
      form.value = proxy.dataToForm(form.value, info)
    } catch (error) {
      visible.value = false
    }
  }

  // 提交表单
  const emit = defineEmits(['submit'])
  async function handleSubmit() {
    try {
      const valid = await formRef.value.validate()
      if (!valid) return
    } catch (error) {
      return
    }
    if (submitting.value) return
    submitting.value = true
    try {
      await proxy.$modal.confirm('确定提交表单数据？')
      if (form.value.id) {
        await editDeptApi(form.value)
      } else {
        await addDeptApi(form.value)
      }
      emit('submit')
      proxy.$modal.msgSuccess('操作成功')
      visible.value = false
    } catch (e) {
      submitting.value = false
    }
  }

  // 获取部门列表
  async function getDeptOptions() {
    try {
      const { list } = await selectDeptApi()
      deptOptions.value = proxy.listToTree(list)
    } catch (e) {}
  }
</script>
